﻿using System.Collections;
using FlowCanvas;
using FlowCanvas.Nodes;
using NodeCanvas.Framework;
using ParadoxNotion.Design;
using UnityEngine;

namespace Yoozoo.Gameplay.Liberty.Nodes
{
    [Category("Ggame")]
    public class PlayEffect : LatentActionNodeBase
    {
        [RequiredField]
        public BBParameter<int> configId;
        [RequiredField]
        public BBParameter<int> effectUniqueId;
        [RequiredField] 
        public BBParameter<string> pointName;

        [HideInInspector]
        public FlowOutput onPlay;

        public override bool allowRoutineQueueing { get { return false; } }

        private bool added = false;
        
        public IEnumerator Invoke()
        {
            yield return new WaitForOneFrame();

            BluePrintPoint point = BlueprintUtils.GetBlueprintPoint(pointName.value);
            if (point!=null)
            {
                BlueprintUtils.PlayEffect(configId.value,effectUniqueId.value,point.position,point.eulerAngles);
                OnPlay();
            }
        }

        private void OnPlay()
        {
            added = true;
            onPlay?.Call(new Flow());
        }
        
        protected override void OnRegisterDerivedPorts(FlowNode node)
        {
            onPlay = node.AddFlowOutput("onPlay");
            node.AddFlowInput("In", (f) => { Begin(Invoke(), f); });
        }

        public override void OnGraphStoped()
        {
            base.OnGraphStoped();
            if (added)
            {
                BlueprintUtils.DestroyEffect(effectUniqueId.value);
            }
            added = false;
        }
    }
}